//摄像头相关错误码
var CW_ERR_CameraNotOpen			=	9000;		//摄像头未打开
var CW_ERR_CameraOpenError			=	9001;		//摄像头打开失败
var CW_ERR_CameraOpenAdy			=	9002;		//摄像头已经打开
var CW_ERR_InitSDK					=	9100;		//初始化SDK失败

//活体状态
var CW_LivenessOK 					= 	0;			//活体并正常获得最佳人脸
var CW_LivenessFailure 				= 	9301;		//未符合活体要求
var CW_LivenessNOFace 				= 	9302;		//未检测到人脸
var CW_LivenessNisNoFace			=	9303;		//红外未检测到人脸
var CW_LivenessLostFace 			= 	9304;		//人脸丢失
var CW_LivenessManyFace 			= 	9305;		//检测到多人
var CW_LivenessFaceChange			=	9307;		//检测到换人
var CW_GetBestFaceErr 				= 	117;		//获取最佳人脸失败

var EnumLocalNetError				=	800;		//网络异常。
var EnumLocalNetErrorUrl			=	803;		//URL格式不正确。
var EnumLocalNetErrorSerAddr		=	806;		//无法解析人脸识别服务主机地址。
var EnumLocalNetErrorConSer			=	807;		//无法连接到人脸识别服务主机。
var EnumLocalNetErrorTimeOut		=	828;		//访问人脸识别服务主机超时。
var EnumLocalNetErrorActData		=	890;		//无法解析人脸识别服务主机返回数据。

var EnumLocalNoFace					=	1100;		//未检测到人脸

var version="1.1.10.0520";
var cloudwalkobj;

var rotatemode = 2;	//0正常 1顺时针90度 2逆时针90度
var open_nis = 1;	//是否开启红外活体检测，1 开启；0 禁止

var open_way = 1;   //0 OPENCV
var VisableLightCameraIndex = "U3405W";	//可见光摄像头ID
var InfraredCameraIndex = "U3403";	//红外光摄像头ID
var rt;       //摄像头错误码
var LiveFaceDate;

$(document).ready(function(){
	
	var w=400;		//640  400  320
	var h=w*3/4;	//宽高比为4：3
	var el = document.getElementById("cloudwalkwebobj");
	createPlugin(el, w, h, version);

	$("#btnBrowse").click(function(){
	  click_browseFile();
	});
	
	$("#bt_chose0").click(function(){
	  click_liveDetect();
	});
	
	$("#bt_chose1").click(function(){
		click_stopCamera();
	});
	
	$("#bt_chose2").click(function(){
		click_startCamera();
	});
	
	$("#bt_chose3").click(function(){
		click_faceVerifyByLocalFile();
	  
	});
});


function createPlugin(targetE,width,height,version) {
	cloudwalkobj = document.createElement("object");
	
	if(0 == rotatemode){
		cloudwalkobj.width = width;
		cloudwalkobj.height = height;
	}else{
		cloudwalkobj.width = height;
		cloudwalkobj.height = width;
	}
	
	cloudwalkobj.id = "CloudWalkSDKPlugin";
	
	var bDet=BrowserDetect.browser;
	if("Explorer"==bDet)
	{
		cloudwalkobj.classid = "CLSID:BD0F48B3-EC69-4107-AF33-107C35D09E2C";	//IE
	}else if("Firefox"==bDet)
	{
		cloudwalkobj.type = "application/x-cloudwalknis";		//Firefox
	}else if("Chrome"==bDet)
	{
		cloudwalkobj.type = "application/x-cloudwalknis";		//Chrome
	}else{
		cloudwalkobj.type = "application/x-cloudwalknis";
	}

	targetE.appendChild(cloudwalkobj);		//所有方法、属性的调用必须在插件添加到页面之后
	
	if(!cloudwalkobj.valid){
		showDownloadNotice();
		return false;
	}
	
	registerCallBack(cloudwalkobj, "cwLivesInfoCallBack", liveDetectEvent);
	registerCallBack(cloudwalkobj, "OnRecvFaceVerify", verifyEvent);			//注册人脸比对的回调方法
	
	cloudwalkobj.cwSetBestImageSave(1, "C:/cloudwalk/bestimg/");		//设置保存最佳人脸图片
	pluginInit(width, height);	
	return true;
}

function pluginInit(width,height) {
	var initRt = cloudwalkobj.cwInit();
	if(0 != initRt)
	{
		alert("ApiKey或SecretKey已过期，请联系技术支持！错误码："+initRt);
		//return;
	}
	
	openCamera();
}

function click_browseFile() {
	showMessage("", result);
	var path=cloudwalkobj.SelectFile();						//选择文件
	if(path.length !=0){
		document.getElementById("local_file").value=path;
	}
}

function click_faceVerifyByLocalFile() {
	var imgPath;
	//imgPath = document.getElementById("local_file").value;
	imgPath = $("#textfield").val();
	//console.log(imgPath);
	if(imgPath.length ==0){
		showMessage("请输入图片路径", result);
	}else{
		showMessage("", result);
		var localImg = cloudwalkobj.cwGetBase64ByLocalFile(imgPath);
		var res = cloudwalkobj.cwFaceCompare(LiveFaceDate, localImg);			//摄像头采集的图片与本地图片进行比对
		verifyEvent(res);
	}
}

function liveDetectEvent(rt) {
	var jsonObj = $.parseJSON(rt);
	
	if(jsonObj.result !=0){
		switch(jsonObj.result)
		{
			case CW_LivenessFailure:
				showMessage("未符合活体要求！", result);
				break;
			case CW_LivenessNOFace:
				showMessage("未检测到人脸！", result);
				break;
			case CW_LivenessLostFace:
				showMessage("人脸丢失！", result);
				break;
			case CW_LivenessManyFace:
				showMessage("检测到多人！", result);
				break;
			case CW_LivenessFaceChange:
				showMessage("检测换人！", result);
				break;
			case CW_GetBestFaceErr:
				showMessage("获取最佳人脸失败！", result);
				break;
			default:
				showMessage("非活体，错误码："+jsonObj.result, result);
				break;
		}
		$("#bestImgObj").attr("src","");
		$("#localImgObj").attr("src","");
	}else{
		showMessage2("活体", result);
		bestImgObj.src = "data:image/jpeg;base64," + jsonObj.image;
		LiveFaceDate = jsonObj.image;
	}
	
	EnableButton();
}

function click_liveDetect() {
	DisableButton();
	result.innerHTML = "";
	bestImgObj.src = "";
	localImgObj.src = "";
	LiveFaceDate = "";
	cloudwalkobj.cwStartLiveDetect();
}

function click_stopCamera() {
	result.innerHTML = "";
	bestImgObj.src = "";
	localImgObj.src = "";
	LiveFaceDate = "";
	cloudwalkobj.cwStopCamera();
	DisableButton();
}

function click_startCamera() {
	EnableButton();
	result.innerHTML = "";
	bestImgObj.src = "";
	localImgObj.src = "";
	LiveFaceDate = "";
	
	openCamera();
}

function openCamera()
{
	//用摄像头名字打开
	//var rt=cloudwalkobj.cwStartCameraEx(VisableLightCameraIndex, InfraredCameraIndex, rotatemode);
	//用摄像头ID打开
	rt = cloudwalkobj.cwStartCamera(); //
	if (0 != rt) {
		switch(rt)
		{
			case CW_ERR_CameraNotOpen:
				showMessage("摄像头未打开！", result);
				break;
			case CW_ERR_CameraOpenError:
				showMessage("摄像头打开失败！", result);
				break;
			case CW_ERR_CameraOpenAdy:
				showMessage("摄像头已经打开！", result);
				break;
			default:
				showMessage("未认证或者摄像头初始化失败 ！错误码："+ rt, result);
				break;
		}
		DisableButton();
		return;
	}else{
		//alert("摄像头初始化成功 ！");
		EnableButton();
	}
}

function DisableButton(){
	$("#bt_chose0").attr("disabled", true);
	$("#bt_chose0").css('background-color','#A3A99C'); 
}

function EnableButton(){
	$("#bt_chose0").attr("disabled", false);
	$("#bt_chose0").css('background-color','#4B8D7C');
}

function showMessage(message, el){
	if(message !== ''){
		el.innerHTML = "";
		var str;
		str = "&nbsp;&nbsp;&nbsp;&nbsp;<strong><font color='red'>";
		str += message;
		str += "</font><strong>";
		el.innerHTML = str;
	}else{
		el.innerHTML = "";
	}
}

function showMessage2(message, el){
	if(message !== ''){
		el.innerHTML = "";
		var str;
		str = "&nbsp;&nbsp;&nbsp;&nbsp;<strong><font color='blue'>";
		str += message;
		str += "</font><strong>";
		el.innerHTML = str;
	}else{
		el.innerHTML = "";
	}
}

function showDownloadNotice(){
	//alert("人脸识别控件未安装");
	$("#downloadNotice").removeClass("hide");
	$("#downloadNotice").addClass("show");
	$("#rside").addClass("hide");
}

function showNewVersionNotice(){
	$("#newVersionNotice").removeClass("hide");
	$("#newVersionNotice").addClass("show");
	$("#rside").addClass("hide");
}

// 注册回调事件(插件名，插件提供的事件名称，调用的JS函数)
function registerCallBack(obj, name, proc) {
	if (typeof(proc) != "function")
		return;
	if (window.ActiveXObject || "ActiveXObject" in window) {
		if (window.ActiveXObject && obj.attachEvent) {
			obj.attachEvent(name, proc);
		} else {
			cloudWalk_AttachIE11Event(obj, name, proc);
		}
	} else {
		obj[name] = proc;
	}
}

// IE11注册回调事件
function cloudWalk_AttachIE11Event(obj, _strEventId, _functionCallback) {
	var nameFromToStringRegex = /^function\s?([^\s(]*)/;
	var paramsFromToStringRegex = /\(\)|\(.+\)/;
	var params = _functionCallback.toString().match(paramsFromToStringRegex)[0];
	var functionName = _functionCallback.name || _functionCallback.toString().match(nameFromToStringRegex)[1];
	var handler;
	try {
		handler = document.createElement("script");
		handler.setAttribute("for", obj.id);
	} catch (ex) {
		handler = document.createElement('<script for="' + obj.id + '">');
	}
	handler.event = _strEventId + params;
	handler.appendChild(document.createTextNode(functionName + params + ";"));
	document.body.appendChild(handler);
}
//人脸比对回调函数
function verifyEvent(rt) {
	EnableButton();
	//var jsonObj = JSON.parse(jsonStr);	//IE6、IE8不兼容
	var jsonObj = $.parseJSON(rt);
	var str="";
	if(jsonObj.result == 0)
	{
		str="人脸相似度："+num(jsonObj.source*100)+"%";
	}else{
		
		if(jsonObj.result == EnumLocalNoFace)
		{
			str += "未检测到人脸！";
		}else{
			str += "人脸对比失败错误码：" + jsonObj.result;
		}
	}

	showMessage(str, result);
}

function num(i) {
	var n = i.toFixed(2);
	return n;
}

function isIE6_8() {
	
	//IE6-8判断(jquery 1.9.0 以上版本支持)
	if(!$.support.leadingWhitespace)
	{
		//alert("IE6-8");
		return 1;
	}

	//以下是IE6-8判断的另外一种方法（无需jquery）
	//var browser=navigator.appName; 
	//if(browser=="Microsoft Internet Explorer")  
	//{   
	//	var b_version=navigator.appVersion;
	//	var version=b_version.split(";");   
	//	var trim_Version=version[1].replace(/[ ]/g,"");  
	//	if(trim_Version=="MSIE8.0"){
	//		return 1;
	//	}else if(trim_Version=="MSIE6.0"){
	//		return 1;
	//	}
	//}
	return 0;
}
